<?php
/**
 * Swolf discription.
 *
 * @copyright Copyright (c) 2015 Swolf Software.
 * @author Liu Xiao<seanliu707@gmail.com>
 */
class UrlManager
{
	/**
	 * @var boolean whether to rewrite URLs. Instead of putting all parameters in the query
	 * string part of a URL.
	 */
	private $urlRewrite = false;
	
	/**
	 * @var string the URL suffix used when in 'path' format.
	 */
	public $suffix = '.html';
	/**
	 * @var boolean whether to show entry script name in the constructed URL. Defaults to true.
	 * This property is used only if [$urlRewrite] is true.
	 */
	public $showScriptName = true;
	/**
	 * @var string the GET parameter name for route. This property is used only if [$urlRewrite] is false.
	 */
	public $routeParam = 'mp';
	
	private $base	= '/';
	private $url	= null;
	private $self	= null;
	
	private $request = null;
	
	public function __construct($rewrite=false)
	{
		$this->url	= $_SERVER['REQUEST_URI'];
		$this->self	= $_SERVER['PHP_SELF'];
		
		if ($this->url[0] != '/') {
			$this->url = '/'.$this->url;
		}
		if ( $this->self[0] != '/' ) {
			$this->self = '/' . $this->self;
		}
		
		if (strrpos($this->self, '/') != false) {
			$this->base = substr($this->self, 0, strrpos($this->self, '/') + 1);
		}
		
		$this->urlRewrite = $rewrite;
	}
	
	public function parseUrl()
	{
		$_spos = 0;	//start position to determine the arguments
		$_len = 0;	//lenth of arguments string
		
		if ($this->urlRewrite == false) {
// 			$_url = substr_replace($this->url, '/', 0, strlen($this->base));
			if (strpos($this->url, '?') != false) {
				$this->request = $_GET;
			}
		} elseif ($this->urlRewrite && $this->showScriptName) {
			$_spos = strpos($this->url, '.php') + 5;
			
			if ($this->suffix != '') {
				$_len = stripos($this->url, $this->suffix) - $_spos;
			} else {
				$_len = strlen($this->url) - $_spos;
			}
			
			$this->request = substr($this->url, $_spos, $_len);
		}
		
		return $this->request;
	}
	
	/**
	 * Creates a URL using the given route and query parameters.
	 * 
	 * For example,
     * // generates: /index.php?r=module/page&param1=value1#name
     * array('module/page', 'param1' => 'value1', '#' => 'name')
     * 
     * @param string|array $params use a string to represent a route,
     * or an array to represent a route with query parameters.
     * @return string the created URL
	 */
	public function createUrl($params)
	{
		$_url = null;
		$params = (array) $params;
		$anchor = isset($params['#']) ? '#' . $params['#'] : '';
		unset($params['#'], $params[$this->routeParam]);
		
		$route = trim($params[0], '/');
		unset($params[0]);
		
		$_url =  $this->showScriptName || !$this->urlRewrite ? $this->self : $this->base;
		
		if ($this->urlRewrite) {
			$len = strlen($_url);
			if ($this->showScriptName && $_url[$len] != '/') {
				$_url .= '/';
			}
			$_url .= $route;
			foreach ($params as $value) {
				$_url .= '/'.$value;
			}
			$_url .= $this->suffix;
		} else {
			$_url .= '?' . $this->routeParam . '='. $route;
			foreach ($params as $key => $value) {
				$_url .= '&' . $key . '=' . $value;
			}
		}
		
		if ($anchor != '') $_url .= $anchor;
		
		return $_url;
	}
	
	/**
	 * Redirect function, default to the index page 
	 * 
	 * @param string $page the requested module, page
	 *     For example, 'course/list'
	 * @param array $args
	 */
	public function redirect($page = null, $args = null)
	{
	    
	    $_url = $this->base;
	    if ($page != null && $args == null) {
	        $_url = $this->createUrl($page);
	    } elseif ($page != null && $args != null) {
	        $param = array();
	        $param[] = $page;
	        $param = array_merge($param, $args);
	        $_url = $this->createUrl($param);
	    }
	    $_uri = Application::getConfig('url');
	    header('Location:' . $_uri['host'] . $_url);
	    exit();
	}
}